// index.js
/* app.js: 小程序初始化js；
app.json: 小程序配置文件，如：导航，窗口，各页面引入；
app.wxss: 小程序公共样式;
各个页面：
Pages：各个子页面以js+json+wxml+wxss组成，方便管理，右边可快捷生成page; 
Pages：每一个子页面都需要写到这个数组里，其实就是路由引入；
Window：系统配置，包括标题，标题颜色，标题背景等（如果不设置分页面配置则默认全覆盖）；
Tabbar：官方提供的导航功能，可以设置导航栏，list为导航数组，存放导航项、color为字体颜色、selectedcolor为选中颜色、backgroundcolor为背景颜色；
globaldata为全局变量
如果要使用请在对应page.js引入：const app = getApp();*/
//import mqtt from '../../utils/mqtt'

var mqtt = require('../../utils/mqtt.min.js')
var client = null
var mss = null


Page({
  data: {
    sbid:'4G终端ID, 一号一ID',
    pic_cheMen: '../tp/车门关.png',
    pic_cheMenSuo: '../tp/车门锁定.png',
    pic_yin_qing: '../tp/发动机熄火.png',
    pic_kong_tiao: '../tp/风机关.png',
    pic_zhi_leng: '../tp/制冷关.png',
    biao_ti: "车生活",
    idd: "",
    id_pass: "",
    id_lp: "",
    sb_id: "",
    zhuang_tai: [false, false, false, false, false], //0men,1che_suo,2che_yin_qing,3che_kong_tiao,4che_zhi_leng

    che_suo: false,
    che_yin_qing: false,
    che_kong_tiao: false,
    che_zhi_leng: false,
    sb_bian_hao:"",
    sbpanDuan:false
  },
  /*打开页面的初始化*/
  onLoad() {
    this.connectmqtt()
  },
  getuser: function (e) { //获取微信信息
    wx.getUserProfile({
      desc: '用于完善会员资料并绑定账户', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        wx.setStorageSync('weiXinMing', res.userInfo.nickName) //同步保存数据 
        wx.setStorageSync('weiXinTuPian', res.userInfo.avatarUrl)
      }
    })
  },

  che_suo: function () {
    if (!this.data.che_suo) {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "men_suo",
        "dong_zuo": "on"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('开锁')
    } else {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "men_suo",
        "dong_zuo": "off"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('关锁')
    }
  },
  che_yin_qing: function () {
    if (!this.data.che_yin_qing) {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "yin_qing",
        "dong_zuo": "on"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('启动')
    } else {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "yin_qing",
        "dong_zuo": "off"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('熄火')
    }
  },
  che_kong_tiao: function () {
    if (!this.data.che_kong_tiao) {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "kong_tiao",
        "dong_zuo": "on"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('开启')
    } else {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "kong_tiao",
        "dong_zuo": "off"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('关闭')
    }
  },
  che_zhi_leng: function () {
    if (!this.data.che_zhi_leng) {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "zhi_leng",
        "dong_zuo": "on"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('制冷')
    } else {
      let zf = {
        "jianQuan": "zhi_xing",
        "ling_pai": this.data.id_lp,
        "bu_wei": "zhi_leng",
        "dong_zuo": "off"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {})
      console.log('常温')
    }
  },

  connectmqtt: function () {
    var czid = "56"
    var zf = {
      "lx": "xcx",
      "id": {
        czid
      },
      "cz": "led"
    }
    var that = this
    var id = Math.floor(Math.random() * 50 + 50) //50到100范围内随机取整数
    var ida = Math.floor(Math.random() * 50 + 50)
    var ids = id.toString()
    var idsa = ida.toString()
    that.data.id = 'yh' + ids+'xcx'+idsa
    const options = {
      connectTimeout: 4000, //连接延时
      clientId: that.data.id,//'yh'+Math.ceil(Math.random()*10), //客户端ID
      port: 443, //WSS协议 端口
      username: 'thingidp@alukwqb|usr_4g|0|MD5', //连接用户名
      password: 'e5bcd8391cafb0eed8db006f7a376a16' //连接密码
    }

    client = mqtt.connect('wxs://alukwqb.iot.gz.baidubce.com/mqtt', options)
    client.on('connect', (e) => {
      console.log('连接成功log')
      console.log(that.data.id)
      client.subscribe('yonghu_shou', {
        qos: 0
      }, function (err) {
        if (!err) {
          console.log('订阅yonghu_shou成功log')
          that.jianquan()
        }
      })
    })
    //监听
    client.on('message', function (topic, message) {
      try {
        let obj = JSON.parse(message.toString())
        mss = JSON.parse(message.toString())
        that.data.megg = JSON.parse(message.toString())

        that.zhixin()
      } catch (e) { // exectionFn函数发生的异常可以及时被catch住
        console.log("不是JSON1")
      }
      console.log("wan...........")

    })
    client.on('reconnect', (error) => {
      console.log('重新连接log', error)
    })
    client.on('error', (error) => {
      console.log('连接失败log', error)
    })
    /*断开
    client.end()
    */
  },

  jianquan: function () { //建立MQTT连接后执行
    var that = this
    if (wx.getStorageSync('id_lp') && wx.getStorageSync('mc')) {
      that.data.id_lp = wx.getStorageSync('id_lp')
      that.data.idd = wx.getStorageSync('mc')
      if (that.data.id_lp != "") {
        //交换令牌
        let zf = {
          "jianQuan": "jiao_huan",
          "idd": that.data.idd,
          "ling_pai": that.data.id_lp,
          "di_zhi": "yonghu_shou"
        }
        let js = JSON.stringify(zf)
        client.publish('fuwuqi', js, function (err) {
          if (err) {
            console.log(err)
          }
        })
      }
    }
    //申请令牌
    else if (wx.getStorageSync('mc') && wx.getStorageSync('ma')) {
      that.data.idd = wx.getStorageSync('mc')
      that.data.id_pass = wx.getStorageSync('ma')
      console.log(that.data.id_pass)
      let zf = {
        "jianQuan": "zhuCe",
        "idd": that.data.idd,
        "id_pass": that.data.id_pass,
        "sb_id": "",
        "di_zhi": "yonghu_shou"
      }
      let js = JSON.stringify(zf)
      client.publish('fuwuqi', js, function (err) {
        if (err) {
          console.log(err)
        }
      })
    } else {
      console.log('请重新登陆账号,核对用户名与密码')
    }
  },

  zhixin: function () { //收到指令执行
    var that = this
    var lp = this.data.id_lp
    console.log(mss)
    if (mss.jianQuan == "shou_quan") {
      if (mss.ling_pai != "") {
        wx.setStorageSync('id_lp', mss.ling_pai)
        that.data.id_lp = mss.ling_pai
        console.log('交换令牌成功')
        setTimeout(() => { //延时800ms
          that.huo_qu_zt()
        }, 800)

      } else {
        console.log('请重新登陆账号,核对用户名与密码')
      }
    } else if (mss.jianQuan == "cha_xun") {
      if (mss.che_men == "on"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_men: true,
          pic_cheMen: '../tp/车门开.png'
        })
      }
      if (mss.che_men == "off"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_men: false,
          pic_cheMen: '../tp/车门关.png'
        })
      }
      if (mss.men_suo == "on"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_suo: true,
          pic_cheMenSuo: '../tp/车门解锁.png'
        })
      }
      if (mss.men_suo == "off"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_suo: false,
          pic_cheMenSuo: '../tp/车门锁定.png'
        })
      }
      if (mss.yin_qing == "on"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_yin_qing: true,
          pic_yin_qing: '../tp/发动机启动.png'
        })
      }
      if (mss.yin_qing == "off"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_yin_qing: false,
          pic_yin_qing: '../tp/发动机熄火.png'
        })
      }
      if (mss.kong_tiao == "on"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_kong_tiao: true,
          pic_kong_tiao: '../tp/风机开.png'
        })
      }
      if (mss.kong_tiao == "off"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_kong_tiao: false,
          pic_kong_tiao: '../tp/风机关.png'
        })
      }
      if (mss.zhi_leng == "on"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_zhi_leng: true,
          pic_zhi_leng: '../tp/制冷开.png'
        })
      }
      if (mss.zhi_leng == "off"&&mss.ling_pai == lp) {
        that.setData({ //同步刷新页面控件
          che_zhi_leng: false,
          pic_zhi_leng: '../tp/制冷关.png'
        })
      }
      console.log("执行完毕")
    } else if (mss.jianQuan == "bang_ding") {
      if(mss.ling_pai == lp && mss.fan_hui =="ok"){
        console.log("终端绑定成功")
      }
      if(mss.ling_pai == lp && mss.fan_hui =="no"){
        console.log("此账号已经绑定了1个终端")
      }
    } else if (mss.yi_chang == "yi_chang") {
      console.log("yi_chang")
    }
  },

  congxindenglu: function () { //清除用户数据
    try {
      wx.setStorageSync('mc', "")
      wx.setStorageSync('ma', "")
      wx.setStorageSync('id_lp', "")
    } catch (e) {
      console.log("cuowu_001")
    }

  },
  sbname:function(e){
    var that = this;
    var valuen = e.detail.value;
    var wordLength = parseInt(valuen.length); //解析字符串长度转换成整数
    if (wordLength!=8) {
      that.setData({
        sbpanDuan:false
      })
      return
    } else{
      that.setData({
        sb_bian_hao:valuen,
        sbpanDuan:true
      })
    } 
  },
  bang_sb:function(e){
    if(this.data.sbpanDuan && this.data.sb_bian_hao!=""){
      if(this.data.id_lp!="" && this.data.idd!="" ){
        let zf = {
          "jianQuan": "bang_ding",
          "ling_pai": this.data.id_lp,
          "idd": this.data.idd,
          "sb_id": this.data.sb_bian_hao,
          "di_zhi": "yonghu_shou"
        }
        let js = JSON.stringify(zf)
        client.publish('fuwuqi', js, function (err) {})
      }else(
        console.log("请先登陆")
      )
    }else{
      console.log("设备ID为8位数")
    }
  },
  huo_qu_zt: function () {
    let zf = {
      "jianQuan": "cha_xun",
      "ling_pai": this.data.id_lp,
      "di_zhi": "yonghu_shou"
    }
    let js = JSON.stringify(zf)
    client.publish('fuwuqi', js, function (err) {})
    console.log('查询状态')
  }






})